import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import {HttpClient} from "@angular/common/http";

@Injectable()
export class HomeService {

  constructor( public http: HttpClient) { }

  //生成报表数据接口
  getData(params): Observable<any> {
    return this.http.get('http://www.bnppzg.com/brands_app/public/index.php/api/Timing/timing', {params})
      .map(this.extractData)
      .catch(this.handleError);
  }
  //生成报表数据接口
  saveData(params): Observable<any> {
    return this.http.get('http://www.bnppzg.com/brands_app/public/index.php/api/Timing/month', {params})
      .map(this.extractData)
      .catch(this.handleError);
  }

  // 获取数据
  getBanner(params): Observable<any> {
    return this.http.get(ROOT_URL + 'home/banner', {params})
      .map(this.extractData)
      .catch(this.handleError);
  }
  //获取排行榜
  getRank(params): Observable<any> {
    return this.http.get(ROOT_URL + 'home/index', {params})
      .map(this.extractData)
      .catch(this.handleError);
  }
  //人气投票
  putVote(params): Observable<any> {
    return this.http.post(ROOT_URL + 'Vote/vote', params)
      .map(this.extractData)
      .catch(this.handleError);
  }
  //获取月榜单
  getEnterpriseRank(params): Observable<any> {
    return this.http.get(ROOT_URL + 'Home/quarterly', {params})
      .map(this.extractData)
      .catch(this.handleError);
  }
  //获取年份榜单
  getEnterpriseYearsRank(params): Observable<any> {
    return this.http.get(ROOT_URL + 'Home/years', {params})
      .map(this.extractData)
      .catch(this.handleError);
  }
  //获取首页背景
  getBackImage(params):Observable<any>{
    return this.http.get(ROOT_URL + "background/index",{params})
      .map(this.extractData)
      .catch(this.handleError)
  }

  private extractData(res: Response) {
    return res;
  }
  private handleError (error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

}
